<template>
  <div class="stock-distribution-container">
    <!-- 图表部分 -->
    <div class="chart-container">
      <div class="chart-header">
        <div class="chart-legend">
          <span class="legend-item">
            <span class="legend-color blue"></span>
            数量
          </span>
          <span class="legend-item">
            <span class="legend-color green"></span>
            金额
          </span>
        </div>
        <div class="chart-title">合计</div>
      </div>
      <div id="chart" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- 导出按钮 -->
    <div style="text-align: left;">
      <el-button @click="exportData">导出</el-button>
    </div>

    <!-- 表格部分 -->
    <el-table 
      :data="tableData" 
      border 
      v-loading="loading"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="index" label="序号" width="80" ></el-table-column>
      <el-table-column prop="wh_name" label="仓库名称" width="150"></el-table-column>
      <el-table-column prop="stk_hand_num" label="库存数量" width="200"  align="center">
        <template #default="scope">
          <span style="color: #409eff;">{{ scope.row.stk_hand_num }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="stk_total" label="库存金额" align="center">
        <template #default="scope">
          <span style="color: #f56c6c;">{{ formatCurrency(scope.row, null, scope.row.stk_total) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 合计行 -->
    <div class="summary-row">
      <span class="summary-label">合计</span>
      <div class="summary-content">
        <span class="summary-quantity">库存数量: <span style="color: #409eff;">{{ totalQuantity }}</span></span>
        <span class="summary-amount">库存金额: <span style="color: #f56c6c;">{{ totalAmount.toFixed(2) }}</span></span>
      </div>
    </div>

    <!-- 分页 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="totalCount"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import http from '../auth/index';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';

export default {
  name: 'StockDistribution',
  setup() {
    const tableData = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalCount = ref(0);
    const chart = ref(null);
    const multipleSelection = ref([]);

    // 统计数据
    const statData = reactive({
      totalWarehouse: 0,
      totalQuantity: 0,
      totalAmount: 0
    });

    // 计算总计
    const totalQuantity = computed(() => {
      return statData.totalQuantity;
    });

    const totalAmount = computed(() => {
      return statData.totalAmount;
    });

    // 格式化货币
    const formatCurrency = (row, column, cellValue) => {
      return parseFloat(cellValue || 0).toFixed(2);
    };

    // 获取数据
    const fetchData = async () => {
      loading.value = true;
      try {
        const response = await http.get('/Stock/GetStockDistribution', {
          params: {
            page: currentPage.value,
            pagesize: pageSize.value
          }
        });

        if (response.data.success && response.data.list) {
          tableData.value = response.data.list;
          totalCount.value = response.data.total;
          
          // 更新统计数据
          statData.totalWarehouse = response.data.total;
          statData.totalQuantity = response.data.total_stk_hand_num;
          statData.totalAmount = response.data.total_stk_total;
          
          // 更新图表
          nextTick(() => {
            initChart();
          });
        } else {
          ElMessage.warning('没有相关数据');
          tableData.value = [];
          totalCount.value = 0;
          statData.totalWarehouse = 0;
          statData.totalQuantity = 0;
          statData.totalAmount = 0;
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取数据失败');
        tableData.value = [];
        totalCount.value = 0;
        statData.totalWarehouse = 0;
        statData.totalQuantity = 0;
        statData.totalAmount = 0;
      } finally {
        loading.value = false;
      }
    };

    // 初始化图表
    const initChart = () => {
      if (!chart.value) {
        const chartDom = document.getElementById('chart');
        if (chartDom) {
          chart.value = echarts.init(chartDom);
        }
      }
      
      if (chart.value && tableData.value.length > 0) {
        const option = {
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: tableData.value.map(item => item.wh_name),
            axisLabel: {
              interval: 0,
              rotate: 0
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '数量',
              position: 'left',
              axisLabel: {
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '金额',
              position: 'right',
              axisLabel: {
                formatter: '{value}'
              }
            }
          ],
          series: [
            {
              name: '数量',
              type: 'bar',
              data: tableData.value.map(item => item.stk_hand_num),
              itemStyle: {
                color: '#5470C6'
              },
              barWidth: '60%'
            },
            {
              name: '金额',
              type: 'line',
              yAxisIndex: 1,
              data: tableData.value.map(item => item.stk_total),
              itemStyle: {
                color: '#91CC75'
              },
              lineStyle: {
                color: '#91CC75'
              },
              symbol: 'circle',
              symbolSize: 6
            }
          ]
        };
        chart.value.setOption(option);
      }
    };

    // 导出数据
    const exportData = () => {
      if (multipleSelection.value.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }

      const header = ['序号', '仓库名称', '库存数量', '库存金额'];
      const data = multipleSelection.value.map(item => [
        item.index,
        item.wh_name,
        item.stk_hand_num,
        item.stk_total.toFixed(2)
      ]);

      const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '库存分布');

      XLSX.writeFile(wb, `库存分布_${new Date().toLocaleDateString()}.xlsx`);
      ElMessage.success('导出成功');
    };

    // 处理选择变化
    const handleSelectionChange = (selection) => {
      multipleSelection.value = selection;
    };

    // 当前页变化 - 改名为handlePageChange
    const handlePageChange = (val) => {
      currentPage.value = val;
      fetchData();
    };

    // 移除handleSizeChange方法，因为新的分页组件不支持页面大小切换

    // 初始化
    onMounted(() => {
      fetchData();
    });

    return {
      tableData,
      loading,
      currentPage,
      totalCount,
      multipleSelection,
      totalQuantity,
      totalAmount,
      formatCurrency,
      exportData,
      handleSelectionChange,
      handlePageChange  // 改为handlePageChange
    };
  }
};
</script>

<style scoped>
.stock-distribution-container {
  padding: 20px;
  background-color: #fff;
}

.chart-container {
  margin: 20px 0;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-legend {
  display: flex;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.blue {
  background-color: #5470C6;
}

.chart-title {
  font-size: 14px;
  color: #666;
}


.summary-row {
  display: flex;
  padding: 15px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  margin-top: 10px;
}

.summary-label {
  font-weight: bold;
  width: 55px; /* 与选择框列宽度相同 */
  text-align: center;
}

.summary-content {
  display: flex;
  flex: 1;
  align-items: center;
}

.summary-quantity {
  font-size: 14px;
  margin-left: 225px; /* 序号80px + 仓库名称150px - 5px调整 */
  width: 120px; /* 与库存数量列宽度相同 */
  text-align: center;
}

.summary-amount {
  font-size: 14px;
  margin-left: 35px; /* 紧接着数量列 */
  flex: 1;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tabs__item) {
  padding: 0 15px;
}

:deep(.el-tabs__item.is-active) {
  border-radius: 4px;
}
</style>
